//
//  CommentViewModel.swift
//  SSComment
//
//  Created by 松松 on 2019/4/25.
//

import Foundation
import UIKit
import Alamofire

public protocol SSMap {
    init(fromDictionary dictionary: [String:Any])
    func toDictionary() -> [String:Any]
}



open class SSCommentViewModel : NSObject{

    private let addCommentURL = "comment/v1/comment/cmComment/add"
    private let getCommentListURL = "comment/v1/comment/cmComment/load"
    private let getCommentReplayListURL = "comment/v1/comment/cmComment/load0"
    private let deleteCommentURL = "comment/v1/comment/cmComment/deleteComment"
    private let likeURL = "comment/v1/comment/cmGiveLike/addGiveLike"
    private let checkIsLikeURL = "comment/v1/comment/cmGiveLike/judgeGiveLike"
    private let cancelLikeURL = "comment/v1/comment/cmGiveLike/cancelGiveLike"
    private let addScoreURL = "comment/v1/comment/cmScore/add"
    private let getGoodCommentsURL = "comment/v1/comment/cmScore/load"
    private let getGoodCommentReplaysURL = "comment/v1/comment/cmScore/load0"
    private let getGoodScoresURL = "comment/v1/comment/cmScore/loadItem"
    private let getUserCommentsURL = "comment/v1/comment/cmScore/loadUser"
    private let getScoreByClassURL = "comment/v1/comment/cmScore/loadScore"
    private let getMainDetialURL = "comment/v1/comment//cmMain/mainTypeDetail"



    public typealias ObjBlock = (ObjModel) -> Void
    public typealias ObjBoolBlock = (ObjBoolModel) -> Void
    public typealias ErrorBlock = (Error) -> Void
    public typealias CommentListBlock = ([CommentListModel]) -> Void
    public typealias GoodCommentsListBlock = ([GoodCommentsListModel]) -> Void
    public typealias GoodScoreBlock = (GoodScoreModel) -> Void
    public typealias ScoresListBlock = ([ScoreListModel]) -> Void
    public typealias MainDetialBlock = (MainDetialModel) -> Void
    public typealias CommentBackBlock = (CmComment) -> Void

    public override init() {

    }


    /// 添加评论
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - fromUserName: 评论人名称
    ///   - fromUserHead: 评论人头像
    ///   - formUserId: 评论人ID
    ///   - commentImages: 评论图片
    ///   - replyCommentId: 回复的评论id
    ///   - commentId: 回复的id
    ///   - mainTypeCode: 主体类型编号
    ///   - toItemCode: 被评价主体id
    ///   - commentContent: 评论内容
    ///   - isImpose: 是否限制评论
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func addComment(appCode: String,
                           fromUserName: String?,
                           fromUserHead: String?,
                           formUserId: String,
                           commentImages: String?,
                           replyCommentId: String?,
                           commentId: String?,
                           mainTypeCode: String,
                           toItemCode: String,
                           commentContent: String,
                           success: CommentBackBlock?,
                           error: ErrorBlock?){

        let paramModel = AddCommentParamModel()
        paramModel.appCode = appCode
        paramModel.fromUserName = fromUserName
        paramModel.fromUserHead = fromUserHead
        paramModel.formUserId = formUserId
        paramModel.commentImages = commentImages
        paramModel.replyCommentId = replyCommentId
        paramModel.mainTypeCode = mainTypeCode
        paramModel.toItemCode = toItemCode
        paramModel.commentContent = commentContent
        paramModel.commentId = commentId

        SSCommentNetWork
            .post(url: addCommentURL,
                  parameter: paramModel.toDictionary(),
                  success: { (model) in
                    guard let modelData = self.map(type: CmComment.self, model) else{return}
                    success?(modelData)
            }) { (err) in
                error?(err)
        }

    }

    /// 获取评论回复列表
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - replyCommentId: 回复的评论id
    ///   - mainTypeCode: 主体类型编号
    ///   - toItemCode: 被评价主体id
    ///   - commentSate: 1:普通评论,2:推荐评论(管理员设置):3:热门评论
    ///   - pageSize: 页数
    ///   - pageNumber: 页码
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func getCommentList(appCode: String,
                               replyCommentId: String?,
                               mainTypeCode: String,
                               toItemCode: String,
                               commentSate : Int,
                               likeNum : Int = 0,
                               pageSize: Int,
                               pageNumber: Int,
                               success: CommentListBlock?,
                               error: ErrorBlock?){

        let paramModel = GetCommentsListParamModel()
        paramModel.appCode = appCode
        paramModel.replyCommentId = replyCommentId
        paramModel.mainTypeCode = mainTypeCode
        paramModel.toItemCode = toItemCode
        paramModel.pageSize = pageSize
        paramModel.pageNumber = pageNumber
        paramModel.commentSate = commentSate
        paramModel.likeNum = likeNum

        SSCommentNetWork
            .request(url: getCommentListURL,
                     parameter: paramModel.toDictionary(),
                     success: { (model) in
                        if let modelData = self.mapArr(type: CommentListModel.self, model){
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 获取回复带评论列表
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - replyCommentId: 回复的评论id
    ///   - mainTypeCode: 主体类型编号
    ///   - toItemCode: 被评价主体id
    ///   - commentSate: 1:普通评论,2:推荐评论(管理员设置):3:热门评论
    ///   - pageSize: 页数
    ///   - pageNumber: 页码
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func getCommentReplayList(appCode: String,
                                     replyCommentId: String?,
                                     mainTypeCode: String,
                                     toItemCode: String,
                                     commentSate : Int,
                                     pageSize: Int,
                                     pageNumber: Int,
                                     success: CommentListBlock?,
                                     error: ErrorBlock?){

        let paramModel = GetCommentsListParamModel()
        paramModel.appCode = appCode
        paramModel.replyCommentId = replyCommentId
        paramModel.mainTypeCode = mainTypeCode
        paramModel.toItemCode = toItemCode
        paramModel.pageSize = pageSize
        paramModel.pageNumber = pageNumber
        paramModel.commentSate = commentSate

        SSCommentNetWork
            .request(url: getCommentReplayListURL,
                     parameter: paramModel.toDictionary(),
                     success: { (model) in
                        if let modelData = self.mapArr(type: CommentListModel.self, model){
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 删除评论
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - mainTypeCode: 主体类型编号
    ///   - toItemCode: 被评价主体id
    ///   - id: 评论ID
    ///   - formUserId: 评论ID
    public func deleteComment(appCode: String,
                              mainTypeCode: String,
                              toItemCode: String,
                              id: Int,
                              formUserId:String,
                              success:ObjBlock?,
                              error:ErrorBlock?){

        SSCommentNetWork
            .request(url: deleteCommentURL,
                     method: .delete,
                     parameter: ["appCode": appCode,
                                 "mainTypeCode": mainTypeCode,
                                 "toItemCode": toItemCode,
                                 "id": id,
                                 "formUserId":formUserId],
                     encoding: URLEncoding.default,
                     success: { (model) in
                        if let modelData = self.map(type: ObjModel.self, model){
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 点赞
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - fromUserName: 被评价人名称
    ///   - fromUserHead: 评价人头像
    ///   - toItemCode: 点赞主体编号
    ///   - mainTypeCode:评论主体编号
    ///   - formUserId: 评价人id
    ///   - goodType: 赞1 / 踩0
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func like(appCode: String,
                     fromUserName: String,
                     fromUserHead: String,
                     toItemCode: String,
                     goodType: Int,
                     mainTypeCode: String,
                     formUserId: String,
                     success: ObjBlock?,
                     error: ErrorBlock?){

        SSCommentNetWork
            .post(url: likeURL,
                  parameter: ["appCode": appCode,
                              "fromUserName": fromUserName,
                              "fromUserHead": fromUserHead,
                              "toItemCode": toItemCode,
                              "mainTypeCode": mainTypeCode,
                              "formUserId": formUserId,
                              "goodType": goodType],
                  success: { (model) in
                    if let modelData = self.map(type: ObjModel.self, model){
                        success?(modelData)
                    }
            }) { (err) in
                error?(err)
        }

    }

    /// 检查是否点赞
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - toItemCode: 点赞主体编号
    ///   - mainTypeCode: 评论主体编号
    ///   - formUserId: 评价人id
    public func checkIsLike(appCode: String,
                            toItemCode: String,
                            mainTypeCode: String,
                            formUserId: String,
                            success: ((Bool) -> Void)?,
                            error: ErrorBlock?){

        SSCommentNetWork
            .request(url: checkIsLikeURL,
                     parameter: ["appCode": appCode,
                                 "toItemCode": toItemCode,
                                 "mainTypeCode": mainTypeCode,
                                 "formUserId": formUserId],
                     success: { (model) in
                        if let modelData = model as? Bool{
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 取消点赞
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - toItemCode: 点赞主体编号
    ///   - mainTypeCode: 评论主体编号
    ///   - formUserId: 评价人id
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func cancelLike(appCode: String,
                           toItemCode: String,
                           mainTypeCode: String,
                           formUserId: String,
                           success: ObjBlock?,
                           error: ErrorBlock?){

        SSCommentNetWork
            .request(url: cancelLikeURL,
                     method: .delete,
                     parameter: ["appCode": appCode,
                                 "toItemCode": toItemCode,
                                 "mainTypeCode": mainTypeCode,
                                 "formUserId": formUserId],
                     encoding: URLEncoding.default,
                     success: { (model) in
                        if let modelData = self.map(type: ObjModel.self, model){
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }


    /// 添加评分
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - toItemCode: 被评价主体id
    ///   - formUserId: 评价人id
    ///   - mainTypeCode: 主体类型编号
    ///   - fromUserName: 评价人名称
    ///   - fromUserHead: 评价人头像
    ///   - score: 评分
    ///   - textString: 返回字符串
    ///   - merchantId: 店铺ID
    ///   - extensions: 订单编号
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func addScore(appCode: String,
                         toItemCode: String,
                         formUserId: String,
                         mainTypeCode: String,
                         fromUserName: String,
                         fromUserHead: String,
                         score: Int,
                         textString: String,
                         merchantId: String,
                         extensions: String,
                         success: ObjBlock?,
                         error: ErrorBlock?){

        SSCommentNetWork
            .post(url: addScoreURL,
                  parameter: ["appCode": appCode,
                              "toItemCode": toItemCode,
                              "formUserId": formUserId,
                              "mainTypeCode": mainTypeCode,
                              "fromUserName": fromUserName,
                              "fromUserHead": fromUserHead,
                              "score": score,
                              "textString": textString,
                              "merchantId": merchantId,
                              "extension": extensions],
                  success: { (model) in
                    if let modelData = self.map(type: ObjModel.self, model){
                        success?(modelData)
                    }
            }) { (err) in
                error?(err)
        }

    }

    /// 获取某个商品所有评价
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - toItemCode: 被评价主体id
    ///   - scoreLevel: 等级
    ///   - mainTypeCode: 主体类型编号
    ///   - pageSize: 页面数
    ///   - pageNumber: 页码数
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func getGoodComments(appCode: String,
                                toItemCode: String,
                                scoreLevel: Int,
                                mainTypeCode: String,
                                pageSize: Int,
                                pageNumber: Int,
                                commentSate: Int,
                                success: GoodCommentsListBlock?,
                                error: ErrorBlock?){

        SSCommentNetWork
            .request(url: getGoodCommentsURL,
                     parameter: ["appCode": appCode,
                                 "toItemCode": toItemCode,
                                 "scoreLevel": scoreLevel,
                                 "mainTypeCode": mainTypeCode,
                                 "pageSize": pageSize,
                                 "pageNumber": pageNumber,
                                 "commentSate": commentSate],
                     success: { (model) in
                        if let modeData = self.mapArr(type: GoodCommentsListModel.self, model){
                            success?(modeData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 获取商品的所有评分统计
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - toItemCode: 被评价主体id
    ///   - mainTypeCode: 主体类型编号
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func getGoodScores(appCode:String,
                              toItemCode:Int,
                              mainTypeCode:String,
                              success:GoodScoreBlock?,
                              error:ErrorBlock?){

        SSCommentNetWork
            .request(url: getGoodScoresURL,
                     parameter: ["appCode":appCode,
                                 "toItemCode":toItemCode,
                                 "mainTypeCode":mainTypeCode],
                     success: { (model) in
                        if let modelData = self.map(type: GoodScoreModel.self, model){
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 获取某个人的所有评论
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - toItemCode: 被评价主体id
    ///   - formUserId: 用户ID
    ///   - mainTypeCode: 主体类型编号
    ///   - pageSize: 页面数
    ///   - pageNumber: 页码数
    public func getUserAllComments(appCode: String,
                                   toItemCode: String,
                                   formUserId: String,
                                   mainTypeCode: String,
                                   pageSize: Int,
                                   pageNumber: Int,
                                   success: CommentListBlock?,
                                   error: ErrorBlock?){

        SSCommentNetWork
            .request(url: getUserCommentsURL,
                     parameter: ["appCode": appCode,
                                 "toItemCode": toItemCode,
                                 "formUserId": formUserId,
                                 "mainTypeCode": mainTypeCode,
                                 "pageSize": pageSize,
                                 "pageNumber": pageNumber],
                     success: { (model) in
                        if let modelData = self.mapArr(type: CommentListModel.self, model){
                            success?(modelData)
                        }
            }) { (err) in
                error?(err)
        }

    }

    /// 按分类查询所有评分
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - mainTypeCode: 主体类型编号
    ///   - pageSize: 页面数
    ///   - pageNumber: 页码数
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func getScoreByClass(appCode:String,
                                mainTypeCode:String,
                                pageSize:Int,
                                pageNumber:Int,
                                success:ScoresListBlock?,
                                error:ErrorBlock?){

        SSCommentNetWork.request(url: getScoreByClassURL,
                                 parameter: ["appCode":appCode,
                                             "mainTypeCode":mainTypeCode,
                                             "pageSize":pageSize,
                                             "pageNumber":pageNumber],
                                 success: { (model) in
                                    if let modelData = self.map(type: ResultListModel<ScoreListModel>.self, model){
                                        success?(modelData.list)
                                    }
        }) { (err) in
            error?(err)
        }

    }

    /// 获取主体详情
    ///
    /// - Parameters:
    ///   - appCode: 应用编号
    ///   - typeCode: 主体编号
    ///   - success: 成功的回调
    ///   - error: 失败的回调
    public func getMainDetian(appCode: String, typeCode: String, success: MainDetialBlock?, error: ErrorBlock?){

        SSCommentNetWork.request(url: getMainDetialURL, parameter: ["appCode": appCode, "typeCode": typeCode], success: { (model) in
            if let modelData = self.map(type: MainDetialModel.self, model){
                success?(modelData)
            }

        }) { (err) in
            error?(err)
        }
    }

}


extension SSCommentViewModel{

    func mapArr<T:SSMap>(type:T.Type,_ arr:Any) ->[T]?{
        if let modelArr = arr as? [[String:Any]]{
            var resultArr = [T]()
            for item in modelArr{
                let ententy = T(fromDictionary: item)
                resultArr.append(ententy)
            }
            return resultArr
        }
        return nil
    }

    func map<T:SSMap>(type:T.Type,_ object:Any) -> T?{
        if let mapDic = object as? [String:Any]{
            let resultModel = T(fromDictionary: mapDic)
            return resultModel
        }
        return nil
    }

}
